<template>
  <div class="user">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container">
      <el-card>
        <div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-input clearable @clear="clearSearch" placeholder="请输入内容" v-model="userSearch">
                <el-button slot="append" icon="el-icon-search" @click="searchUsers"></el-button>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="dialogUserVisible=true">添加用户</el-button>
            </el-col>
          </el-row>
        </div>
        <el-table stripe :data="tableData" border style="width: 100%">
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column prop="username" label="姓名" width="180"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
          <el-table-column prop="mobile" label="电话" width="180">
            <template v-slot="scope">{{scope.row.mobile | phone}}</template>
          </el-table-column>
          <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
          <el-table-column prop="mg_state" label="状态" width="180">
            <template slot-scope="scope">
              <el-switch @change="changeUserState(scope.row)" v-model="scope.row.mg_state"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="edit" label="操作">
            <template v-slot="scope">
              <el-button
                size="mini"
                type="primary"
                @click="editUserBtn(scope.row)"
                icon="el-icon-edit"
              ></el-button>
              <el-button
                size="mini"
                type="danger"
                @click="delTips(scope.row.id)"
                icon="el-icon-delete"
              ></el-button>
              <el-tooltip
                :enterable="false"
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
              >
                <el-button
                  size="mini"
                  type="warning"
                  @click="setRoleBtn(scope.row.id)"
                  icon="el-icon-setting"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            :page-sizes="[2, 3, 4, 5]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @next-click="changePage"
            @prev-click="changePage"
            @current-change="changePage"
            @size-change="changeSizePage"
          ></el-pagination>
        </div>
      </el-card>
      <!-- 添加用户的弹窗 -->
      <el-dialog
        title="添加用户"
        width="50%"
        @closed="closeAddUserDialog"
        :visible.sync="dialogUserVisible"
      >
        <el-form
          :model="userForm"
          :rules="userRules"
          ref="userForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="userForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addUser">确 定</el-button>
          <el-button @click="dialogUserVisible = false">取 消</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户的弹窗 -->
      <el-dialog
        title="添加用户"
        width="50%"
        @closed="closeEditUserDialog"
        :visible.sync="dialogEditUserVisible"
      >
        <el-form
          :model="editUserForm"
          :rules="editUserRules"
          ref="refEditUser"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogEditUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色的弹窗 -->
      <el-dialog
        title="分配角色"
        @closed="clearRoleCur"
        :visible.sync="dialogSetRightsVisible"
        width="30%"
      >
        <div>
          <div class="setRow">
            <span>当前的用户 :</span>
            <span>{{curUser}}</span>
          </div>
          <div class="setRow">
            <span>当前的角色 :</span>
            <span>{{curRole}}</span>
          </div>
          <div class="setRow">
            <span>分配新角色 :</span>
            <el-select v-model="selectRoles" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogSetRightsVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRole">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    const validatorPwd = (rule, value, cb) => {
      const regPwd = /^[a-zA-Z0-9_]{3,16}$/
      if (regPwd.test(value)) {
        return cb()
      }
      cb(new Error('请输入6-16位包含数字字母下划线的密码'))
    }
    const validatorMobile = (rule, value, cb) => {
      const regMobile = /^0?(13|14|15|18|17)[0-9]{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      // 用户数据
      tableData: [],
      // 所有角色的用户列表
      rolesList: [],
      userDataInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      curUser: '', // 当前用户
      curRole: '', // 当前用户角色
      // 一共多少条用户数据
      total: 0,
      // 搜索用户
      userSearch: '',
      // 控制添加用户弹窗
      dialogUserVisible: false,
      dialogEditUserVisible: false, // 控制编辑用户弹窗
      // 控制分配角色的弹窗
      dialogSetRightsVisible: false,
      // 分配角色时的id
      selectRoleId: '',
      // 角色下拉列表
      selectRoles: '',
      userForm: {
        // 添加用户表单数据
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editUserForm: {
        // 编辑用户表单数据
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      // 添加用户的表单规则验证
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatorPwd, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入email', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确邮箱',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatorMobile, trigger: 'blur' }
        ]
      },
      // 编辑用户的表单规则验证
      editUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入email', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确邮箱',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatorMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUsers()
    this.getRolesList()
  },
  methods: {
    async getUsers() {
      const { data: res } = await this.$axios.get('users', {
        params: this.userDataInfo
      })
      this.pagenum = res.data.pagenum
      this.total = res.data.total
      this.tableData = res.data.users.reverse()
    },
    async getRolesList() {
      const { data: res } = await this.$axios.get('roles')
      this.rolesList = res.data
    },
    async changeUserState(val) {
      const { data: res } = await this.$axios.put(
        `users/${val.id}/state/${val.mg_state}`
      )
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message.error('修改状态失败')
      }
      this.$message.success('状态修改成功')
    },
    // 下一页
    changePage(curPage) {
      this.userDataInfo.pagenum = curPage
      this.getUsers()
    },
    // 每页显示条数
    changeSizePage(size) {
      this.userDataInfo.pagesize = size
      this.getUsers()
    },
    // 模糊查询用户
    searchUsers() {
      this.userDataInfo.query = this.userSearch
      this.getUsers()
    },
    // 清空查询条件
    clearSearch() {
      this.userDataInfo.query = ''
      this.getUsers()
    },

    // 添加用户
    addUser() {
      this.$refs.userForm.validate(async vaild => {
        if (vaild) {
          const { data: res } = await this.$axios.post('users', this.userForm)
          if (res.meta.status === 201) {
            this.getUsers()
            return this.$message.success('添加用户成功')
          }
        }
        this.$message.error('添加用户失败')
      })

      this.dialogUserVisible = false
    },
    // 编辑用户
    editUser() {
      this.$refs.refEditUser.validate(async valid => {
        if (!valid) {
          return this.$message.error('修改用户失败')
        }
        const { data: res } = await this.$axios.put(
          'users/' + this.editUserForm.id,
          {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改用户失败')
        this.getUsers()
        this.$message.success('用户修改成功')
        this.dialogEditUserVisible = false
      })
    },
    // 关闭添加用户弹窗事件
    closeAddUserDialog() {
      this.$refs.userForm.resetFields()
    },
    // 编辑用户
    async editUserBtn(userInfo) {
      const { data: res } = await this.$axios.get('users/' + userInfo.id)
      if (res.meta.status !== 200) return this.$message.error('没获取到此用户')
      this.editUserForm.id = res.data.id
      this.editUserForm.username = res.data.username
      this.editUserForm.email = res.data.email
      this.editUserForm.mobile = res.data.mobile
      this.dialogEditUserVisible = true
    },
    // 关闭编辑用户弹窗
    closeEditUserDialog() {
      this.$refs.refEditUser.resetFields()
    },
    // 删除用户
    delTips(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$axios.delete('/users/' + id)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUsers()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配角色弹窗
    async setRoleBtn(id) {
      this.selectRoleId = id

      // 查询用户
      const { data: userRes } = await this.$axios.get('users/' + id)
      if (userRes.meta.status !== 200) {
        return this.$message.error('获取用户失败')
      }
      this.curUser = userRes.data.username
      let roleid = userRes.data.rid

      // 查询用户角色
      const { data: roleRes } = await this.$axios.get('roles/' + roleid)
      if (roleRes.meta.status !== 200)
        return this.$message.error('获取用户角色失败')
      this.curRole = roleRes.data.roleName
      this.dialogSetRightsVisible = true
    },
    // 分配角色
    async setRole() {
      const { data: res } = await this.$axios.put(
        `users/${this.selectRoleId}/role`,
        {
          rid: this.selectRoles
        }
      )
      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.getUsers()
      this.$message.success('分配角色成功')
      this.dialogSetRightsVisible = false
    },
    clearRoleCur() {
      this.selectRoles = ''
    }
    // choiseList() {
    //   // 选中的下拉列
    //   console.log(this.selectRoles)
    // }
  },
  // 过滤手机号码
  filters: {
    phone: value => {
      // 先隐身转换为字符串
      value = '' + value
      let arr = value.split('')
      arr.splice(3, 4, '****')
      return arr.join('')
      // return value.substr(0, 3) + '****' + value.substr(7)
    }
  }
}
</script>

<style lang='less' scoped>
.container {
  width: 100%;
  background: #fff;
  border-radius: 5px;
  box-shadow: 2px 5px 5px #ddd;
}
.setRow {
  line-height: 30px;
  font-size: 16px;
}
.setRow span {
  padding: 0 5px;
}
</style>
